package com.hyst.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hyst.common.Contants;
import com.hyst.common.ResultBean;
import com.hyst.domain.Admin;
import com.hyst.service.LoginService;
import com.hyst.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.hyst.domain.Student;


@Controller
@RequestMapping("login")
@CrossOrigin(maxAge = 3600, origins = "*")
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 登录页
     */
    @GetMapping
    public String getLoginPage(HttpServletRequest request) {
        Object obj = request.getSession().getAttribute(Contants.SESSION_USER_INFO);
        if (obj != null && obj instanceof Admin) {
            return "index";
        }
        return "login";
    }


    /**
     * 用户登录
     */
    @PostMapping(value = "/check")
    @ResponseBody
    public ResultBean login(@RequestParam("loginName") String loginName,
                            @RequestParam("password") String password,
                            HttpServletRequest request,
                            HttpServletResponse response) {
        return loginService.login(loginName, password, request, response);
    }


    /**
     * 用户注销
     */
    @GetMapping(value = "/destory")
    public String destory(HttpServletRequest request, HttpServletResponse response) {
        try {
            Admin user = (Admin) request.getSession().getAttribute(Contants.SESSION_USER_INFO);
            if (user != null) {
                request.getSession().removeAttribute(Contants.SESSION_USER_INFO);
            }
            CookieUtil.removeCookie(response, Contants.COOKIE_LOGIN_PWD);
            CookieUtil.removeCookie(response, Contants.COOKIE_LOGIN_NAME);
            CookieUtil.removeCookie(response, Contants.SESSION_NAME);
        } catch (Exception e) {
            System.out.println(e);
        }
        return "redirect:/login";
    }


    @GetMapping("validate")
    public String login(Student student) {
        return "success";
    }


    // 2018-9-25 chenbin: 新增
    @PostMapping("setUID/{uid}")
    public static String getUIDFromSession(@PathVariable("uid") String uid) {
        String uniqueId = "uniqueId";
        try {
            getRequest().getSession().setAttribute("uniqueid", uid);
        } catch (Exception e) {

        }
        uniqueId = uid;
        return uniqueId;
    }


    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attrs.getRequest();
    }
}
